<template>
  <a-modal
    :title="modalTitle"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
  >
    <a-form :form="form">
      <a-form-item v-show="false" >
        <a-input v-decorator="['id']" type="hidden"/>
      </a-form-item>
      <a-form-item
        label="单号"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-input
          disabled
          v-decorator="['no']" />
      </a-form-item>
      <!--<a-form-item
        label="类型"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-select  @change="typeChange" v-decorator="['type', {rules: [{required: true, message: '类型不能为空'}]}]" placeholder="请选择">
          <a-select-option
            v-for="(label,value) in typeMap"
            :key="value"
            :label="label"
            :value="parseInt(value)">{{ label }}
          </a-select-option>
        </a-select>
      </a-form-item>-->
      <a-form-item
        label="出库仓库id"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
        v-show="false"
      >
        <a-input
          v-decorator="['storeId', {rules: [{required: true, message: '出库id不能为空'}]}]" />
      </a-form-item>
      <a-form-item
        label="出库仓库"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-input
          disabled
          style="width:70%;margin-right:5px"
          v-decorator="['storeName', {rules: [{required: true, message: '仓库名称不能为空'}]}]" />
        <a-button type="primary" @click="handleStoreSelect(1)">选择仓库</a-button>
      </a-form-item>
      <a-form-item
        label="入库仓库id"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
        v-show="false"
      >
        <a-input
          v-decorator="['inStoreId', {rules: [{required: true, message: '入库id不能为空'}]}]" />
      </a-form-item>
      <a-form-item
        label="入库仓库"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-input
          disabled
          style="width:70%;margin-right:5px"
          v-decorator="['inStoreName', {rules: [{required: true, message: '仓库名称不能为空'}]}]" />
        <a-button type="primary" @click="handleStoreSelect(2)">选择仓库</a-button>
      </a-form-item>

      <a-form-item
        label="备注"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-textarea
          :rows="4"
          v-decorator="['remark', {rules: [{required: false, message: '备注不能为空'}]}]"/>
      </a-form-item>
    </a-form>
    <a-tabs type="card" default-active-key="1">
      <a-tab-pane key="1" tab="调拨详情">
        <div class="table-operator">
          <a-button size="small" type="primary" @click="handleSpareStoreSelect">
            <a-icon type="plus"/>
            添加
          </a-button>
          <a-button class="margin-left8" size="small" type="danger" @click="handleDel">
            <a-icon type="delete"/>
            删除
          </a-button>
        </div>
        <a-table
          bordered
          :data-source="data"
          :columns="columns"
          tableLayout="auto"
          rowKey="id"
          :row-selection="rowSelection">
          <span slot="action" slot-scope="record">
            <template>
              <a @click="handleDetailSelect(record)">修改</a>
              <a-divider type="vertical" />
              <a-popconfirm title="是否要删除该条数据？" @confirm="handleDelOne(record.id)">
                <a>删除</a>
              </a-popconfirm>
            </template>
          </span>
        </a-table>
      </a-tab-pane>
    </a-tabs>

    <detail-base-form ref="detailBaseForm" @selected="handleDetailSelected"/>
    <template slot="footer">
      <a-button :loading="confirmLoading" type="primary" @click="save()">保存</a-button>
    </template>
    <store-select-modal ref="storeSelectModal" @selected="handleStoreSelected"/>
    <spare-store-select-modal ref="spareStoreSelectModal" @selected="handleSpareStoreSelected"/>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { addOutStoreForm, updateOutStoreForm } from '@/api/store/transferstoreform'
import DetailBaseForm from './DetailBaseForm'
import StoreSelectModal from '@/views/store/store/modules/StoreSelectModal'
import SpareStoreSelectModal from '@/views/store/sparestore/modules/SpareStoreSelectModal'

export default {
  name: 'BaseOutStoreForm',
  components: {
    DetailBaseForm,
    StoreSelectModal,
    SpareStoreSelectModal
  },
  data () {
    return {
      confirmLoading: false,
      modalTitle: null,
      form: this.$form.createForm(this),
      visible: false,
      type: 1,
      storeId: null,
      inStoreId: null,
      flag: 0,
      // 下拉框map
      typeMap: {},
      // 表头
      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          customRender: (text, record, index) => {
            return index + 1
          }
        },
        {
          title: '备件名称',
          dataIndex: 'spareId',
          customRender: (text, record, index) => {
            return record.spareName
          }
        },
        {
          title: '规格型号',
          dataIndex: 'ggxh'
        },
        {
          title: '原厂编号',
          dataIndex: 'initNo'
        },
        {
          title: '库存数量',
          dataIndex: 'storeNum'
        },
        {
          title: '调拨数量',
          dataIndex: 'num'
        },
        {
          title: '调拨价格',
          dataIndex: 'price',
          customRender: (text, record, index) => {
            return this.BaseTool.Amount.formatter(text)
          }
        },
        {
          title: '调拨总价',
          dataIndex: 'totalPrice',
          customRender: (text, record, index) => {
            return this.BaseTool.Amount.formatter(text)
          }
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      data: [],
      selectedRowKeys: [],
      selectedRows: [],
      options: {
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys
        }
      },
      rowSelection: {
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys
          this.selectedRows = selectedRows
        }
      }
    }
  },
  props: {
  },
  created () {
    // 下拉框map
    this.typeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.OUT_STORE_FORM_TYPE)
  },
  methods: {
    base (record) {
      this.visible = true
      // 如果是空标识添加
      if (this.BaseTool.Object.isBlank(record)) {
        this.modalTitle = '添加'
        this.data = []
        return
      }
      this.modalTitle = '编辑'
      this.storeId = record.storeId
      this.inStoreId = record.inStoreId
      const { form: { setFieldsValue } } = this
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign(pick(record, [
          'id',
          'no',
          'storeId',
          'inStoreId',
          'storeName',
          'inStoreName',
          // 'totalPrice',
          // 'type',
          'remark'
        ])))
      })
      this.data = record.detailList
    },
    save () {
      const { form: { validateFieldsAndScroll } } = this
      this.confirmLoading = true
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          this.confirmLoading = false
          return
        }
        if (this.data.length === 0) {
          this.$message.error('请添加出库详情')
          this.confirmLoading = false
          return
        }
        values.detailList = this.data
        // 日期处理
        if (this.BaseTool.String.isBlank(values.id)) {
          addOutStoreForm(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        } else {
          updateOutStoreForm(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    handleCancel (values) {
      this.visible = false
      this.confirmLoading = false
      this.form.resetFields()
      if (this.BaseTool.Object.isNotBlank(values)) {
        this.$emit('ok', values)
      }
    },
    typeChange (values) {
      this.type = values
    },
    handleStoreSelect (value) {
      this.flag = value
      this.$refs.storeSelectModal.base({}, {})
    },
    handleStoreSelected (record, keys, rows) {
      const [ key ] = keys
      const [ row ] = rows
      const { form: { setFieldsValue } } = this
      if (this.flag === 1) {
        this.storeId = key
        this.$nextTick(() => {
          setFieldsValue(Object.assign({
            'storeId': key,
            'storeName': row.name
          }))
        })
      }
      if (this.flag === 2) {
        this.inStoreId = key
        this.$nextTick(() => {
          setFieldsValue(Object.assign({
            'inStoreId': key,
            'inStoreName': row.name
          }))
        })
      }
    },
    handleSpareStoreSelect () {
      if (this.storeId == null || this.inStoreId == null) {
        this.$message.error('请先选择出入仓库')
        return
      }
      this.$refs.spareStoreSelectModal.base({}, { storeId: this.storeId, num: 0 })
    },
    handleSpareStoreSelected (record, keys, rows) {
      const { data } = this
      for (let i = 0; i < rows.length; i++) {
        var find = false
        for (let j = 0; j < data.length; j++) {
          if (rows[i].id === data[j].id || rows[i].spareId === data[j].spareId) {
            find = true
            break
          }
        }
        if (!find) {
          const selectData = rows[i]
          const storeNum = rows[i].num
          selectData.num = 1
          selectData.storeNum = storeNum
          selectData.totalPrice = selectData.price
          data.push(selectData)
        }
      }
    },
    handleDetailSelect (record) {
      if (this.storeId == null || this.inStoreId == null) {
        this.$message.error('请先选择出入仓库')
        return
      }
      if (this.storeId === this.inStoreId) {
        this.$message.error('出库和入库不能为同一个')
        return
      }
      this.$refs.detailBaseForm.base(record)
    },
    handleDetailSelected (values) {
      console.log(values.num)
      console.log(values.price)
      console.log(values.totalPrice)
      const newData = [...this.data]
      for (let j = 0; j < newData.length; j++) {
        if (values.id === newData[j].id) {
          newData[j].num = values.num
          newData[j].price = values.price
          newData[j].totalPrice = values.totalPrice
          break
        }
      }
      this.data = newData
    },
    handleDel () {
      const data = [...this.data]
      if (this.selectedRowKeys.length === 0) {
        this.$message.error('请至少选择一条数据')
        return
      }
      this.data = data.filter(item => !this.selectedRowKeys.includes(item.id))
    }
  }
}
</script>
